package com.dy.course.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.dy.course.common.BaseController;
import com.dy.course.common.ResponseMessage;
import com.dy.course.entity.ResourceInfo;
import com.dy.course.model.Resource;
import com.dy.course.service.IResourceService;

@Controller
public class ResourceController extends BaseController{
	
	@Autowired
	IResourceService resourceService;
	
	@Value("${file.baseDir}")
	private String baseDir;

	@RequestMapping(value="/resource/select")
	@ResponseBody
	public ResponseMessage<List<Resource>> login(ResourceInfo info){
		logger.info("【图片查询信息】参数信息,info = "+JSON.toJSONString(info));
		return constructResponse(resourceService.qureyResource(info));
	} 
	
	
	@RequestMapping(value="/resource/upload",method=RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<?> register(ResourceInfo info, @RequestParam MultipartFile[] myfiles, HttpServletRequest request){
		logger.info("【图片上传】参数信息,info = "+JSON.toJSONString(info));
		 for(MultipartFile myfile : myfiles){
	            if(myfile.isEmpty()){
	            	logger.info("文件上传失败,info = "+JSON.toJSONString(myfile));
	            }else{
	            	info.setUrl(myfile.getOriginalFilename());
	            	String prefix=myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".")+1);
	            	info.setExtension(prefix);
	                //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中  
	                String realPath = baseDir;
	                //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的  
	                try {
						FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
					} catch (IOException e) {
						e.printStackTrace();
					}
	            }
	        }
		resourceService.upload(info);
		return constructNullResponse();  
	}
}
